const { createProxyMiddleware } = require('http-proxy-middleware');

// 从环境变量获取代理目标
const SWAGGER_PROXY_TARGET = process.env.SWAGGER_PROXY_TARGET || 'http://localhost:6700';
const API_PROXY_TARGET = process.env.API_PROXY_TARGET || 'http://localhost:3001';

// Swagger API 代理配置
const swaggerProxy = createProxyMiddleware({
  target: SWAGGER_PROXY_TARGET,
  changeOrigin: true,
  pathRewrite: {
    '^/swagger-api': ''
  },
  onProxyRes: function(proxyRes, req, res) {
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
    proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
    proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';
  },
  onError: (err, req, res) => {
    console.error('Swagger Proxy Error:', err);
    res.status(500).json({
      error: 'Proxy Error',
      message: err.message || 'Failed to connect to Swagger service'
    });
  },
  logLevel: 'debug'
});

// 本地 API 代理配置
const localApiProxy = createProxyMiddleware({
  target: API_PROXY_TARGET,
  changeOrigin: true,
  pathRewrite: {
    '^/local-api': ''
  },
  // 添加错误处理
  onError: (err, req, res) => {
    console.error('Local API Proxy Error:', err);
    res.status(500).json({
      error: 'Proxy Error',
      message: 'Failed to connect to local API service'
    });
  },
  // 添加日志
  logLevel: 'debug'
});

// 导出代理配置
module.exports = {
  swaggerProxy,
  localApiProxy
}; 